import Vue from "vue";
import VueRouter from "vue-router";
import Crud from "./components/axiosCRUD/crud"
import MyTable from "./components/MyTable"
import Test from "./components/test"
import ElementUI from "./components/element-test/index.vue"
import Admin from "./components/admin/index"
import AdminHome from "./components/admin/home"
import AdminList from "./components/admin/list"
import Login from "./components/admin/login"

Vue.use(VueRouter)

const routes = [
  {
    path: "/crud",
    name: "crud",
    component: Crud
  },
  {
    path: "/test",
    name: "test",
    component: Test
  },
  {
    path: "/mytable",
    name: "mytable",
    component: MyTable
  },
  {
    path: "/element",
    name: "element",
    component: ElementUI,
    redirect: "/element/home",
    children: [
      {
        path: "/element/home",
        name: "elementHome",
        component: () => import("./components/element-test/home"),
      },
      {
        path: "/element/login",
        name: "elementLogin",
        component: () => import("./components/element-test/login"),
      },
      {
        path: "/element/register",
        name: "elementRegister",
        component: () => import("./components/element-test/register"),
      }
    ]
  },
  {
    path: "/admin",
    name: "admin",
    component: Admin,
    redirect: "/admin/home",
    children: [
      {
        path: "list",
        name: "adminList",
        component: AdminList
      },
      {
        path: "home",
        name: "adminHome",
        component: AdminHome
      },
      {
        path: "login",
        name: "login",
        component: Login
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  routes
})

// 解决导航重复点击报错问题
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

router.beforeEach((to, from, next) => {
  // next是继续访问
  if (/^\/admin\/*/.test(to.path)) {
    if (to.path !== "/admin/login") {
      if (localStorage.getItem("user")) {
        next()
      } else {
        alert("请先登录！")
        next("/admin/login")
      }
    } else {
      next()
    }

  } else {
    next()
  }
})

export default router;